package com.warmlight.voicepacket;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.data.eventbus.LoginFloat;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.data.eventbus.StopFloatService;
import com.warmlight.voicepacket.data.eventbus.TeaseHideFloat;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.widget.FloatInfo;
import com.warmlight.voicepacket.widget.FloatPlayList;
import com.warmlight.voicepacket.widget.FloatPlayListDetail;
import com.warmlight.voicepacket.widget.FloatSetting;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

/**
 * Created by jason on 2018/5/24.
 */

public class FloatWindowService extends Service {

    private static final String TAG = "FloatWindowService";
    private RelativeLayout rl_float_container,rl_float_detail,rl_float_content_container,mSettingLayout,mInfoLayout;
    private FloatPlayList mPlaylistLayout;
    private FloatPlayListDetail mLastPlaylistDetailLayout;
    private LinearLayout ll_float_title,ll_title_detail;
    private TextView tv_float_title_detail;
    //布局参数.
    private WindowManager.LayoutParams params;
    //实例化的WindowManager.
    private WindowManager windowManager;

    private ImageView iv_float_icon;

    //状态栏高度.（接下来会用到）
    private int statusBarHeight = -1;

    @Override
    public void onCreate() {
        super.onCreate();
        createWindow();
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void onEvent(StopFloatService data){
        if(data == null){
            Log.i(TAG,"StopFloatService == null");
            return;
        }
        stopSelf();
    }

    /**
     * 变声录音的时候隐藏悬浮框
     * @param teaseHideFloat
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxxxx(TeaseHideFloat teaseHideFloat){
        boolean show = teaseHideFloat.isShow();
        if (show){
            if (rl_float_container != null) {
                rl_float_container.setVisibility(View.VISIBLE);
            }
        }else{
            if (rl_float_container != null) {
                rl_float_container.setVisibility(View.GONE);
            }
        }

    }

//    private void isShowFloat( boolean show){
//        if (show){
//            if (rl_float_container != null) {
//                rl_float_container.setVisibility(View.VISIBLE);
//            }
//        }else{
//            if (rl_float_container != null) {
//                rl_float_container.setVisibility(View.GONE);
//            }
//        }
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxxx(LoginFloat login){
        UserCenterData userCenterData = login.getUserCenterData();
        if (rl_float_content_container != null) {
            rl_float_content_container.removeAllViews();
            rl_float_content_container.addView(mPlaylistLayout == null ?mPlaylistLayout= new FloatPlayList(getApplicationContext()) : mPlaylistLayout);
        }
        if (mPlaylistLayout != null) {
            mPlaylistLayout.refresh(userCenterData);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxx(Login login){
        if (rl_float_content_container != null) {
            rl_float_content_container.removeAllViews();
            rl_float_content_container.addView(mPlaylistLayout == null ?mPlaylistLayout= new FloatPlayList(getApplicationContext()) : mPlaylistLayout);
        }
        if (mPlaylistLayout != null) {
            mPlaylistLayout.notifyPlaylist();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(NotifyMyPlaylist data){
        if(rl_float_content_container!=null){
            rl_float_content_container.removeAllViews();
            rl_float_content_container.addView(mPlaylistLayout == null ?mPlaylistLayout= new FloatPlayList(getApplicationContext()) : mPlaylistLayout);
        }
        if(mPlaylistLayout!=null){
            mPlaylistLayout.notifyPlaylist();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(params!=null){
            SPUtils.setParamX(params.x);
            SPUtils.setParamY(params.y);
        }
        if(windowManager!=null && rl_float_container != null){
            windowManager.removeView(rl_float_container);
        }
    }

    private void createWindow(){
        //赋值WindowManager&LayoutParam.
        params = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置type.系统提示型窗口，一般都在应用程序窗口之上.
        //params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //for android 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0+
//            params.type = WindowManager.LayoutParams.TYPE_TOAST;
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
//            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
//            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            }
        }

        //设置效果为背景透明.
        params.format = PixelFormat.RGBA_8888;
        //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        //设置窗口初始停靠位置.
        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.x = SPUtils.getParamX();
        params.y = SPUtils.getParamY();

        //设置悬浮窗口长宽数据.
        //注意，这里的width和height均使用px而非dp.这里我偷了个懒
        //如果你想完全对应布局设置，需要先获取到机器的dpi
        //px与dp的换算为px = dp * (dpi / 160).
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局.
        rl_float_container = (RelativeLayout) inflater.inflate(R.layout.service_float_window,null);

        //添加toucherlayout
        try {

            windowManager.addView(rl_float_container,params);

        }catch (Exception e){
//            e.printStackTrace();
        }

        //主动计算出当前View的宽高信息.
        rl_float_container.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);

        //用于检测状态栏高度.
        int resourceId = getResources().getIdentifier("status_bar_height","dimen","android");
        if (resourceId > 0)
        {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
//        Log.i("TAG","状态栏高度为:" + statusBarHeight);

        //浮动窗口按钮.
        iv_float_icon = (ImageView) rl_float_container.findViewById(R.id.iv_float_icon);
        iv_float_icon.setVisibility(View.VISIBLE);
        iv_float_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(),"点击了悬浮窗",Toast.LENGTH_SHORT).show();
            }
        });

        //内容容器
        rl_float_content_container = (RelativeLayout) rl_float_container.findViewById(R.id.rl_float_content_container);

        //整个内容容器与icon并列，非全局容器
        rl_float_detail = (RelativeLayout) rl_float_container.findViewById(R.id.rl_float_detail);
        rl_float_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //null
            }
        });
        rl_float_detail.setVisibility(View.GONE);

        //悬浮窗列表title
        ll_float_title = (LinearLayout) rl_float_container.findViewById(R.id.ll_float_title);
        ll_float_title.setVisibility(View.VISIBLE);
        //悬浮窗详情title
        ll_title_detail = (LinearLayout) rl_float_container.findViewById(R.id.ll_title_detail);
        ll_title_detail.setVisibility(View.GONE);
        //悬浮窗详情文字提示
        tv_float_title_detail = (TextView) rl_float_container.findViewById(R.id.tv_float_title_detail);

        //创建设置界面
        mSettingLayout = new FloatSetting(getApplicationContext());
        //创建说明页面
        mInfoLayout = new FloatInfo(getApplicationContext());
        //创建播放列表页面
        mPlaylistLayout = new FloatPlayList(getApplicationContext());

        rl_float_content_container.removeAllViews();
        rl_float_content_container.addView(mPlaylistLayout);
        mPlaylistLayout.setOnPlaylistClickListener(new FloatPlayList.PlaylistClickListener() {
            @Override
            public void ItemClicked(DBFloatPlaylist data) {
                if(data == null){
                    return;
                }
                rl_float_detail.setBackgroundResource(R.drawable.background_float_back);
                tv_float_title_detail.setText(data.getList_name());
                ll_float_title.setVisibility(View.GONE);
                ll_title_detail.setVisibility(View.VISIBLE);
                mLastPlaylistDetailLayout = new FloatPlayListDetail(getApplicationContext(),data);
                rl_float_content_container.removeAllViews();
                rl_float_content_container.addView(mLastPlaylistDetailLayout);
                //添加悬浮窗播单点击的埋点
                MobclickAgent.onEvent(getApplicationContext(),MobClickHelper.FLOAT_CLOT,data.getList_name());
                HashMap<String,Object> temp = new HashMap<>();
                temp.put("添加悬浮窗播单点击的埋点",data.getList_name());
                ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_CLOT,temp);

                //
                ClickLog.clickLog(ClickLog.float_clot,data.getId()+"","0");
            }
        });

        //列表收起按钮
        rl_float_detail.findViewById(R.id.tv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_float_detail.setVisibility(View.GONE);
                iv_float_icon.setVisibility(View.VISIBLE);
                //在播放列表页面的收起埋点，目前埋点产品统计成了一个
                MobclickAgent.onEvent(getApplicationContext(),MobClickHelper.FLOAT_FOLD);
                ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_FOLD);

            }
        });

        //说明按钮
        rl_float_detail.findViewById(R.id.tv_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_float_detail.setBackgroundResource(R.drawable.background_float_back);
                tv_float_title_detail.setText("说明");
                ll_float_title.setVisibility(View.GONE);
                ll_title_detail.setVisibility(View.VISIBLE);
                rl_float_content_container.removeAllViews();
                rl_float_content_container.addView(mInfoLayout == null ? new FloatInfo(getApplicationContext()) : mInfoLayout);
                //说明按钮埋点
                MobclickAgent.onEvent(getApplicationContext(), MobClickHelper.FLOAT_EXP);
                ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_EXP);
                //
                ClickLog.clickLog(ClickLog.float_exp,"0","0");
            }
        });

        //设置按钮
        rl_float_detail.findViewById(R.id.tv_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_float_detail.setBackgroundResource(R.drawable.background_float_back);
                tv_float_title_detail.setText("设置");
                ll_float_title.setVisibility(View.GONE);
                ll_title_detail.setVisibility(View.VISIBLE);
                rl_float_content_container.removeAllViews();
                rl_float_content_container.addView(mSettingLayout == null ? new FloatSetting(getApplicationContext()) : mSettingLayout);
                //设置按钮埋点
                MobclickAgent.onEvent(getApplicationContext(),MobClickHelper.FLOAT_SETING);
                ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_SETING);
                //
                ClickLog.clickLog(ClickLog.float_seting,"0","0");

            }
        });

        //悬浮窗详情title后退按钮
        ll_title_detail.findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_float_detail.setBackgroundResource(R.drawable.background_float_noback);
                ll_title_detail.setVisibility(View.GONE);
                ll_float_title.setVisibility(View.VISIBLE);
                rl_float_content_container.removeAllViews();
                rl_float_content_container.addView(mPlaylistLayout == null ? new FloatPlayList(getApplicationContext()) : mPlaylistLayout);
                mPlaylistLayout.requestFocus();
            }
        });

        //收起按钮逻辑相同，时间不够再写一遍
        ll_title_detail.findViewById(R.id.tv_close1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_float_detail.setVisibility(View.GONE);
                iv_float_icon.setVisibility(View.VISIBLE);
                //在播放列表详情页页面的收起埋点，目前埋点产品统计成了一个
                MobclickAgent.onEvent(getApplicationContext(),MobClickHelper.FLOAT_FOLD);
                ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_FOLD);
                //
                ClickLog.clickLog(ClickLog.float_fold,"0","0");
            }
        });

        addTouchAction();

    }

    //添加随手势操作逻辑
    private void addTouchAction(){
        iv_float_icon.setOnTouchListener(new View.OnTouchListener() {
            int lastX, lastY;
            int paramX, paramY;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                params.x = (int) event.getRawX() - 150;
//                //这就是状态栏偏移量用的地方
//                params.y = (int) event.getRawY() - 150 - statusBarHeight;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        params.x = paramX + dx;
                        params.y = paramY + dy;
                        // 更新悬浮窗位置
                        windowManager.updateViewLayout(rl_float_container,params);
                        break;
                    case MotionEvent.ACTION_UP:
                        if(Math.abs(lastX -  (int) event.getRawX()) < 5 && Math.abs(lastY - (int) event.getRawY()) < 5){
                            rl_float_detail.setVisibility(View.VISIBLE);
                            iv_float_icon.setVisibility(View.GONE);
                            //点击悬浮窗按钮的埋点
                            MobclickAgent.onEvent(getApplicationContext(),MobClickHelper.FLOAT_UNFOLD);
                            ZhugeSDK.getInstance().track(getApplicationContext(),MobClickHelper.FLOAT_UNFOLD);

                            //
                            ClickLog.clickLog(ClickLog.float_unfold,"0","0");
                        }
                        break;
                }
                // 更新悬浮窗位置

                return false;
            }
        });

        rl_float_detail.setOnTouchListener(new View.OnTouchListener() {
            int lastX, lastY;
            int paramX, paramY;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        params.x = paramX + dx;
                        params.y = paramY + dy;
                        // 更新悬浮窗位置
                        windowManager.updateViewLayout(rl_float_container,params);
                        break;
                    case MotionEvent.ACTION_UP:
//                        if(Math.abs(lastX -  (int) event.getRawX()) < 5 && Math.abs(lastY - (int) event.getRawY()) < 5){
//                            Toast.makeText(getApplicationContext(),"up2",Toast.LENGTH_SHORT).show();
//                        }
                        break;
                }

                return false;
            }
        });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {

        public void isShowWindow(TeaseHideFloat show){
            xxxxxx(show);
        }

    }
}
